<template>
  <div class="app-container">
    <!-- 分页查询 -->
    <el-form
      ref="queryParams"
      :model="queryParams"
      size="small"
      label-suffix=":"
      label-width="120px"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item
            :label="$t('batchInventoryLang.inventoryType')"
            prop="stockType"
          >
            <el-select
              v-model="queryParams.stockType"
              :placeholder="$t('pleaseEnter')"
              style="width: 200px"
            >
              <el-option
                v-for="item in stockTypeOptions"
                :key="item.value"
                :value="item.value"
                :label="$t('regionLang.' + item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('locationLang.pickType')" prop="pickType">
            <el-select
              v-model="queryParams.pickType"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in locationPickTypeOptionList"
                :key="item.value"
                :value="item.value"
                :label="$t('locationLang.' + item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('depotLang.depot')" prop="depotId">
            <el-select
              v-model="queryParams.depotId"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in depotOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item
            :label="$t('harvestLang.customerName')"
            prop="customerId"
          >
            <el-select
              v-model="queryParams.customerId"
              :placeholder="$t('harvestLang.customerName')"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="item in customerOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item
            :label="$t('goodsSKULang.skuCode')"
            prop="skuCode"
          >
            <el-input
              v-model="queryParams.skuCode"
              :placeholder="$t('goodsSKULang.skuCode')"
              clearable
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item prop="dateTime">
            <template #label>
              <el-select
                v-model="queryParams.dateType"
                @change="changeDateType"
              >
                <el-option :value="0" :label="$t('shelfDate')" />
                <el-option :value="1" :label="$t('gmtModified')" />
              </el-select>
            </template>
            <el-date-picker
              v-model="queryParams.dateTime"
              type="datetimerange"
              value-format="timestamp"
              :range-separator="$t('to')"
              :start-placeholder="$t('beginDate')"
              :end-placeholder="$t('endDate')"
              @change="changeDateTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item
            :label="$t('locationLang.locationCode')"
            prop="locationCode"
          >
            <el-input
              v-model="queryParams.locationCode"
              :placeholder="$t('pleaseEnter')"
              maxlength="50"
              show-word-limit
              clearable
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item :label="$t('outboundOrderLang.orderType')" prop="orderType">
            <el-select
              v-model="queryParams.orderType"
              :placeholder="$t('pleaseSelect')"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in orderTypeOptionList"
                :key="item.value"
                :value="item.value"
                :label="$t('locationLang.' + item.title)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item label="冻结状态" prop="freezeStockFlag">
            <el-select v-model="queryParams.freezeStockFlag" placeholder="请选择冻结状态">
              <el-option label="未冻结" :value="0" />
              <el-option label="已冻结" :value="1" />
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("reset") }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" size="small" icon="el-icon-download" @click="exportToExcel">
            {{ $t("warehousingLang.inventoryExport") }}
          </el-button>
        </el-col>
      </el-row>
      <el-row v-if="false" :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="plain"
            size="medium"
            icon="el-icon-download"
            @click="exportInventory"
          >
            {{ $t("inventoryExport") }}
          </el-button>
          <el-button
            type="plain"
            size="medium"
            icon="el-icon-upload"
            @click="importInventory"
          >
            {{ $t("inventoryImport") }}
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- 数据列表 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      border
      class="mt-10"
    >
      <!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column type="index" width="55" align="center" />
      <el-table-column
        :label="$t('goodsSKULang.baseSkuInfoDTO')"
        prop="skuCode,goodsName,skuWeight,skuSize"
        align="left"
        min-width="240"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("goodsSKULang.skuCode") + " : " }}
            <span>{{ scope.row.skuCode }}</span>
          </p>
          <p>
            {{ $t("goodsSKULang.goodsName") + " : " }}
            <span>{{ scope.row.goodsName }}</span>
          </p>
          <p>
            {{ $t("goodsSKULang.weight") + "(KG)" + " : " }}
            <span>{{ scope.row.skuWeight }}</span>
          </p>
          <p>
            {{ $t("unitLang.size") + "(CM)" + " : " }}
            <span>{{ scope.row.skuSize }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('warehousingLang.packageType')"
        prop="packageType"
        min-width="120px"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{
            $t(
              "warehousingLang." +
                getTitleByValue(packageTypeOptions, scope.row.packageType)
            )
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('goodsSKULang.customerCodeAndName')"
        prop="customerCodeAndName"
        align="center"
        min-width="150"
      />
      <el-table-column
        :label="$t('goodsSKULang.depotCodeAndName')"
        prop="depotCodeAndName"
        align="center"
        min-width="160"
      />
      <el-table-column
        :label="
          $t('goodsSKULang.storageLocation')
        "
        align="left"
        min-width="180"
        prop="locationCodeAndPickTypeName"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("goodsSKULang.storageLocation") + " : "
            }}<span>{{ scope.row.locationCodeAndPickTypeName }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('harvestLang.warehouseNumber')"
        prop="orderNo"
        align="center"
        min-width="100"
      />
      <el-table-column
        :label="$t('outboundOrderLang.orderType')"
        prop="orderType"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <span>{{
            $t(
              "locationLang." +
                getTitleByValue(orderTypeOptionList, scope.row.orderType)
            )
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('goodsSKULang.numberOfShelves')"
        prop="shelvingNum"
        align="center"
        min-width="80"
      />
      <el-table-column
        :label="$t('goodsSKULang.canUseStock')"
        prop="canUseStock"
        align="center"
        min-width="100"
      />
      <el-table-column
        :label="$t('outboundOrderLang.freeze')"
        prop="freezeStock"
        align="center"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            :disabled="scope.row.freezeStock === 0 ? true : false"
            @click="getWaitOutList(scope.row)"
          >{{ scope.row.freezeStock }}</el-button>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('warehousingLang.stockAge')"
        prop="locationAge"
        align="center"
        min-width="120"
      />
      <el-table-column
        :label="$t('batchInventoryLang.inventoryType')"
        prop="stockType"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <span>{{
            $t(
              "regionLang." +
                getTitleByValue(stockTypeOptions, scope.row.stockType)
            )
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operationDate')"
        prop="gmtShelving,gmtModified"
        align="center"
        min-width="220"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("shelfDate") + " : " }}
            <span>{{ scope.row.gmtShelving }}</span>
          </p>
          <p>
            {{ $t("gmtModified") + " : " }}
            <span>{{ scope.row.gmtModified }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operation')"
        align="center"
        min-width="150px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button v-if="false" type="text" @click="handleMove(scope.row)">
            {{ $t("inventoryLang.moveInventory") }}
          </el-button>
          <el-button type="text" @click="handleAdjust(scope.row)">
            {{ $t("inventoryLang.inventoryTransfer") }}
          </el-button>
          <el-button type="text" @click="handleHistory(scope.row)">
            {{ $t("historys") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 50, 100, 200, 1000, 2000, 5000]"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
        @size-change="handleSizeChange"
      />
    </el-row>
    <!-- 待出库库存 -->
    <el-dialog
      :title="$t('outboundOrderLang.freeze')"
      :visible.sync="waitOutDialog"
      width="80%"
    >
      <el-table
        ref="form"
        v-loading="loading"
        :data="waitOutData"
        border
        class="mt-10"
      >
        <el-table-column
          :label="$t('tableIndex')"
          type="index"
          align="center"
          width="80"
        />
        <el-table-column
          :label="$t('outboundOrderLang.orderNo')"
          prop="orderNo"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('outboundOrderLang.freezeOrderType')"
          prop="orderType"
          align="center"
          min-width="160"
        >
          <template slot-scope="scope">
            {{
              $t(
                "locationLang." +
                  getTitleByValue(
                    freezeOrderTypeOptionList,
                    scope.row.orderType
                  )
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('goodsSKULang.skuCode')"
          prop="skuCode"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('depotLang.depot')"
          prop="depotName"
          align="center"
          min-width="120"
        />
        <el-table-column
          :label="$t('outboundOrderLang.freeze')"
          prop="frozenNum"
          align="center"
          min-width="160"
        />

        <el-table-column
          :label="$t('createDate')"
          prop="gmtCreatedTime"
          align="center"
          min-width="120"
        />
      </el-table>
    </el-dialog>
    <!-- 移库存 -->
    <el-dialog
      :visible.sync="moveInventoryDialog"
      :title="$t('inventoryLang.moveInventory')"
      width="auto"
    >
      <el-form
        ref="moveRef"
        :rules="rules"
        :model="moveInventoryForm"
        label-suffix=":"
        label-width="120px"
      >
        <el-form-item :label="$t('goodsSKULang.skuCode')" prop="skuCode">
          <span>{{ moveInventoryForm.skuCode }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('batchInventoryLang.currentInventory')"
          prop="currentInventory"
        >
          <span> {{ moveInventoryForm.skuCode }} </span>
        </el-form-item>
        <el-form-item
          :label="$t('batchInventoryLang.currentLocation')"
          prop="currentLocation"
        >
          <span> {{}} </span>
        </el-form-item>
        <el-form-item
          :label="$t('batchInventoryLang.targetLocation')"
          prop="targetLocation"
        >
          <el-input
            v-model="moveInventoryForm.targetLocation"
            :placeholder="$t('batchInventoryLang.targetLocation')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item
          :label="$t('batchInventoryLang.moveNumber')"
          prop="moveNumber"
        >
          <el-input
            v-model="moveInventoryForm.moveNumber"
            :placeholder="$t('batchInventoryLang.moveNumber')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('batchInventoryLang.reason')" prop="reason">
          <el-input
            v-model="moveInventoryForm.reason"
            :placeholder="$t('batchInventoryLang.reason')"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="end">
        <el-button type="warning" plain szie="midumn" @click="cancel">{{
          $t("cancel")
        }}</el-button>
        <el-button
          type="primary"
          szie="midumn"
          @click="handleSubmitNewInventory"
        >{{ $t("confirm") }}</el-button>
      </el-row>
    </el-dialog>
    <!-- 调库存 -->
    <el-dialog
      :visible.sync="adjustInventoryDialog"
      :title="$t('inventoryLang.inventoryTransfer')"
      width="580px"
    >
      <el-form
        ref="adjustForm"
        :model="adjustInventoryForm"
        size="small"
        :rules="adjustRules"
        label-suffix=":"
        label-width="100px"
      >
        <el-form-item
          :label="$t('batchInventoryLang.currentInventory')"
          prop="currentInventory"
        >
          <span>{{ adjustInventoryForm.canUseStock }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('batchInventoryLang.inventoryAdjustment')"
          prop="adjustStock"
        >
          <el-input
            v-model="adjustInventoryForm.adjustStock"
            :placeholder="$t('pleaseEnter')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('batchInventoryLang.reason')" prop="adjustReason">
          <el-input
            v-model="adjustInventoryForm.adjustReason"
            :placeholder="$t('pleaseEnter')"
          />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="end">
        <el-button type="warning" plain szie="midumn" @click="cancel">{{
          $t("cancel")
        }}</el-button>
        <el-button type="primary" szie="midumn" @click="handleSubmit">{{
          $t("confirm")
        }}</el-button>
      </el-row>
    </el-dialog>
    <!-- 导入库存 -->
    <el-dialog
      :visible.sync="importInventoryDialog"
      :title="$t('inventoryImport')"
      width="580px"
    >
      <el-form
        ref="importForm"
        :model="importInventoryForm"
        size="small"
        label-suffix=":"
        label-width="100px"
      >
        <el-form-item
          :label="$t('template')"
        >
          <span style="width: 100%; color: #0096d7; cursor: pointer;" @click="downloadTemplate">{{ $t('templateDownload') }}</span>
        </el-form-item>
        <el-form-item :label="$t('uploadFile')" prop="adjustReason">
          <el-upload
            class="upload-excel"
            action="//jsonplaceholder.typicode.com/posts/"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            accept=".xlsx, .xls"
          >
            <el-button size="small" type="primary">点击上传库存文件Excel</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="end">
        <el-button type="warning" plain szie="midumn" @click="importInventoryDialog = false">{{
          $t("cancel")
        }}</el-button>
        <el-button type="primary" szie="midumn" @click="handleSubmit">{{
          $t("confirm")
        }}</el-button>
      </el-row>
    </el-dialog>
    <el-dialog
      :visible.sync="batchLogOpen"
      width="1200px"
    >
      <div>
        <el-table :data="batchLogLists">
          <el-table-column prop="batchId" label="批次" />
          <el-table-column prop="orderNo" label="移库单" />
          <el-table-column prop="operationType" label="操作类型">
            <template slot-scope="scope">
              <span>{{ formatOperationType(scope.row.operationType) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="beforeNum" label="变更前数量" />
          <el-table-column prop="afterNum" label="变更后数量" />
          <el-table-column prop="sourceLocationCode" label="来源库位" />
          <el-table-column prop="targetLocationCode" label="变更库位" />
          <el-table-column prop="gmtCreated" label="时间">
            <template slot-scope="scope">
              <span>{{ formatTimestamp(scope.row.gmtCreated) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="操作人" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDepotListAllStatus } from '@/api/business/depotManage/depot'
import {
  depotRegionTypeDict,
  locationPickTypeDict,
  packageTypeDict,
  deliveryStatusDict,
  orderTypeDict,
  freezeOrderTypeDict
} from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import { getCustomerNameList } from '@/api/business/inventoryManage/inventory'
import {
  getStockBatchPageList,
  getWaitOutList,
  adjustStockBatchStock,
  getBatchLogList
} from '@/api/business/inventoryManage/batchInventory.js'
import * as XLSX from 'xlsx';
export default {
  name: 'BatchInventory',
  components: {},
  data() {
    return {
      total: 0,
      loading: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        stockType: null, // 库存类型
        pickType: null, // 拣货类型
        orderType: null, // 订单类型
        depotId: null,
        customerId: null,
        freezeStockFlag: null,
        skuCode: null,
        dateType: 0, // 默认选中上架日期
        shelvingDateStart: null,
        shelvingDateEnd: null,
        modifiedDateStart: null,
        modifiedDateEnd: null,
        containerCode: undefined,
        locationCode: undefined
      },
      tableData: [],
      waitOutData: [],
      waitOutDialog: false, // 待出库
      moveInventoryDialog: false,
      adjustInventoryDialog: false,
      batchLogOpen: false,
      moveInventoryForm: {},
      adjustInventoryForm: {},
      importInventoryForm: {},
      depotOptionList: [], // 仓库下拉
      customerOptionList: [], // 客户名称下拉
      getTitleByValue: getTitleByValue,
      deliveryStatusDict: deliveryStatusDict,
      deliveryStatusOptoins: getDictOptionList(deliveryStatusDict),
      stockTypeOptions: getDictOptionList(depotRegionTypeDict), // 库存类型下拉
      packageTypeOptions: getDictOptionList(packageTypeDict), // 包装类型
      locationPickTypeOptionList: getDictOptionList(locationPickTypeDict), // 拣货类型下拉
      orderTypeOptionList: getDictOptionList(orderTypeDict), // 订单类型下拉
      freezeOrderTypeOptionList: getDictOptionList(freezeOrderTypeDict), // 冻结订单类型
      adjustRules: {
        adjustStock: {
          required: true,
          message: this.$t('pleaseEnter'),
          trigger: 'blur'
        },
        reason: {
          required: true,
          message: this.$t('pleaseEnter'),
          trigger: 'blur'
        }
      },
      rules: {},
      importInventoryDialog: false,
      batchLogLists: []
    }
  },
  created() {
    this.getDepotListAllStatus()
    this.getCustomerNameList()
    this.getStockBatchPageList()
  },
  methods: {
    // 处理时间戳
    handleTimeStamp(dateTime) {
      if (dateTime) {
        const timestamp = dateTime.map((item) => item / 1000)
        console.log(timestamp) // 时间选择器
        // 上架时间
        if (this.queryParams.dateType === 0) {
          this.queryParams.shelvingDateStart = timestamp[0]
          this.queryParams.shelvingDateEnd = timestamp[1]
        } else if (this.queryParams.dateType === 1) {
          this.queryParams.modifiedDateStart = timestamp[0]
          this.queryParams.modifiedDateEnd = timestamp[1]
        }
      }
    },
    changeDateTime(dateTime) {
      this.handleTimeStamp(dateTime)
      console.log(this.queryParams.dateTime)
    },
    changeDateType(val) {
      this.handleReset()
      console.log(val)
      this.queryParams.dateType = val
    },
    // 查询
    handleQuery() {
      this.loading = true
      this.queryParams.pageNo = 1
      this.getStockBatchPageList()
      this.loading = false
    },
    async handleReset() {
      // await this.$refs.queryParams.resetFields();
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        stockType: null, // 库存类型
        pickType: null, // 拣货类型
        depotId: null,
        customerId: null,
        skuCode: null,
        dateType: 0, // 默认选中上架日期
        shelvingDateStart: null,
        shelvingDateEnd: null,
        modifiedDateStart: null,
        modifiedDateEnd: null
      }
      this.getStockBatchPageList()
    },
    // 获取仓库下拉
    async getDepotListAllStatus() {
      const res = await getDepotListAllStatus()
      if (!res) return
      this.depotOptionList = res.data || []
    },
    // 获取客户名称下拉
    async getCustomerNameList() {
      const { data } = await getCustomerNameList()
      console.log(data, '客户名称')
      this.customerOptionList = data
    },
    // 批次库存列表
    async getStockBatchPageList() {
      const { data } = await getStockBatchPageList({
        ...this.queryParams,
      })
      this.tableData = data.stockBatchList
      this.total = data.totalRowNum
    },
    // // 待出库列表
    async getWaitOutList(row) {
      console.log('row', row)
      const { data } = await getWaitOutList({
        customerId: row.customerId,
        skuId: row.skuId,
        depotId: row.depotId,
        orderNo: row.orderNo,
        batchId: row.batchId,
      })
      this.waitOutDialog = true
      this.waitOutData = data
    },
    // 移库存
    async handleMove() {
      console.log('待定')
      this.moveInventoryDialog = true
    },
    //  调库存
    async handleAdjust(row) {
      console.log('待确定')
      this.adjustInventoryForm = row
      console.log(row.locationId)
      this.adjustInventoryDialog = true
    },
    // 查看调整库存历史记录
    async handleHistory(row) {
      const orderNo = row.orderNo;
      try {
        const response = await getBatchLogList(4, orderNo);
        this.batchLogLists = response.data;
        console.log(this.batchLogLists);
        this.batchLogOpen = true
      } catch (error) {
        console.error('请求发生错误：', error);
      }
    },
    cancel() {
      this.moveInventoryDialog = false
      this.adjustInventoryDialog = false
    },
    async handleSubmit() {
      const { data } = await adjustStockBatchStock({
        caseUseStock: this.adjustInventoryForm.canUseStock,
        adjustReason: this.adjustInventoryForm.adjustReason,
        adjustStock: this.adjustInventoryForm.adjustStock,
        batchId: this.adjustInventoryForm.batchId,
        locationId: this.adjustInventoryForm.locationId,
        orderNo: this.adjustInventoryForm.orderNo,
        modifiedUser: 15
      })
      console.log(data);
      this.$message({
        message: '调库存成功',
        type: 'success'
      })
      this.adjustInventoryDialog = false
    },
    handleSubmitNewInventory() {
      console.log('移库存')
    },
    pageNoChange(newPage) {
      this.queryParams.pageNo = newPage
      this.getStockBatchPageList()
    },
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNo = 1
      this.getStockBatchPageList()
    },
    exportInventory() {
      // todo
    },
    importInventory() {
      this.importInventoryDialog = true
    },
    beforeUpload(file) {
      console.log(file)
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel'
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isExcel) {
        this.$message.error('上传的文件不是Excel!')
      }
      if (!isLt50M) {
        this.$message.error('上传的文件大小不能超过 50MB!')
      }
      return isExcel && isLt50M
    },
    handleSuccess(file) {
      console.log(file)
    },
    downloadTemplate() {
      window.open('./batchInventoryTemplate.xlsx?v=' + Number(new Date()), '_self')
    },
    formatOperationType(operationType) {
      switch (operationType) {
        case 0:
          return '增加';
        case 1:
          return '扣减';
        default:
          return '未知类型';
      }
    },
    formatTimestamp(timestamp) {
      const date = new Date(timestamp * 1000);
      return date.toLocaleString();
    },
    // 批次库存导出
    exportToExcel() {
      console.log('原始数据：', this.tableData);
      const data = this.tableData;
      const fileName = '批次库存数据.xlsx';
      const workbook = XLSX.utils.book_new();
      const customHeaders = [
        '可用库存',
        '锁定库存',
        '批次库存 ID',
        'skuId',
        'SKU',
        '产品名称',
        '重量',
        '长*宽*高：cm',
        '包裹类型',
        '客户 ID',
        '客户代码/名称',
        '仓库 ID',
        '仓库代码/名称',
        '库位',
        '流转箱 Code',
        '流转箱尺寸：长*宽*高',
        '单号：入库/退件',
        '单号：入库/退件类型',
        '待上架',
        '待出库',
        '库龄',
        '库存类型(0表示标准)',
        '上架日期',
        '更新日期'
      ];
      const newData = data.map(item => {
        const newItem = {};
        customHeaders.forEach((header, index) => {
          const key = Object.keys(item)[index];
          if (header.indexOf('流转箱') < 0) {
            if (key === 'locationCode') {
              newItem[header] = item[key] ? item[key].join(',') : '';
            } else if (key === '库存类型') {
              console.log(`原始库存类型值：${item[key]}, 类型：${typeof item[key]}`);
              newItem[header] = item[key] === 0 ? '标准' : item[key];
              console.log(`处理后的库存类型值：${newItem[header]}`);
            } else {
              newItem[header] = item[key];
            }
          }
        });
        return newItem;
      });
      console.log('处理后的数据：', newData);
      const worksheet = XLSX.utils.json_to_sheet(newData, {
        header: [
          '可用库存',
          '锁定库存',
          '批次库存 ID',
          'skuId',
          'SKU',
          '产品名称',
          '重量',
          '长*宽*高：cm',
          '包裹类型',
          '客户 ID',
          '客户代码/名称',
          '仓库 ID',
          '仓库代码/名称',
          '库位',
          '单号：入库/退件',
          '单号：入库/退件类型',
          '待上架',
          '待出库',
          '库龄',
          '库存类型(0表示标准)',
          '上架日期',
          '更新日期'
        ],
        skipHeader: false
      });
      // 自适应列宽
      const columnWidths = {};
      worksheet['!cols'] = [];
      customHeaders.forEach((header, index) => {
        const maxLength = newData.reduce((max, row) => Math.max(max, (row[header] || '').toString().length), 0);
        columnWidths[index] = maxLength < 10 ? 10 : maxLength;
        worksheet['!cols'].push({ wch: columnWidths[index] });
      });
      XLSX.utils.book_append_sheet(workbook, worksheet, '批次库存数据');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.click();
      URL.revokeObjectURL(url);
    }
  }
}
</script>

<style></style>
